
package edu.weber.bookstore.database;

import edu.weber.bookstore.util.DatabaseConnection;
import edu.weber.bookstore.util.DatabaseModel;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 
 * 
 */
public class Author extends DatabaseModel
{
	/**
	 * table tied to the database
	 */
	protected static String TABLE_NAME = "authors";
	private String _name;
	private String _description;
	
	/**
	 * Constructor for an Author
	 * @param id primary key
	 * @param name the displayed name for the author (Commonly first and last name)
	 * @param description a text description or bio of an author
	 */
	public Author(int id, String name, String description)
	{
		super(id);
		_name = name;
		_description = description;
	}
	
	/**
	 * Returns an author by the desired ID
	 * @param id the primary key of the author
	 * @return an Author object associated with the primary key
	 * @throws SQLException 
	 */
	public static Author find(int id) throws SQLException
	{
		Author author = null;
		
		PreparedStatement pm = DatabaseConnection.getConnection().prepareStatement("SELECT * FROM ".concat(TABLE_NAME).concat(" WHERE id = ?;"));
		pm.setInt(1, id);
		
		ResultSet rs = pm.executeQuery();
		
		int id_in = rs.findColumn("id");
		int name_in = rs.findColumn("name");
		int description_in = rs.findColumn("description");
		if(rs.next())
		{
			author = new Author(rs.getInt(id_in), rs.getString(name_in), rs.getString(description_in));
		}
		return author;
	}
	
	@Override
	protected String getTableName()
	{
		return TABLE_NAME;
	}

	/**
	 * Unimplemented
	 * @throws SQLException 
	 */
	@Override
	protected void create() throws SQLException
	{
		throw new SQLException("No database table tied to this model.");
	}
	
	/**
	 * Unimplemented
	 * @throws SQLException 
	 */
	@Override
	protected void update() throws SQLException
	{
		throw new SQLException("No database table tied to this model.");
	}
	
	/**
	 * 
	 * @return the display name for the author 
	 */
	public String getName()
	{
		return _name;
	}
	
	/**
	 * 
	 * @return the description/bio of the author.
	 */
	public String getDescription()
	{
		return _description;
	}
	
	/**
	 * 
	 * @param name the desired display name of the Author
	 */
	public void setName(String name)
	{
		_name = name;
	}
	
	/**
	 * 
	 * @param description the desired description/bio of the Author
	 */
	public void setDescription(String description)
	{
		_description = description;
	}
}
